package com.cms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cms.common.Constants;
import com.cms.common.QueryPageParam;
import com.cms.controller.dto.UserDTO;
import com.cms.entity.User;
import com.cms.exception.ServiceException;
import com.cms.mapper.UserMapper;
import com.cms.service.IUserService;
import com.cms.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

//@Service
@Service("iUserService")
public class IUserServiceImpl extends ServiceImpl<UserMapper, User>implements IUserService {

    private static final Log LOG = Log.get();

    @Override
    public UserDTO login(UserDTO userDTO){
        User one = getUserInfo(userDTO);
        if (one != null){
            BeanUtil.copyProperties(one,userDTO,true);
            //设置token
            String token = TokenUtils.genToken(one.getId().toString(),one.getPassword());
            userDTO.setToken(token);
            return userDTO;
        }else {
            throw new  ServiceException(Constants.CODE_600,"用户名或密码错误");
        }

        //这是第二种方式
//        List<User> list = list(queryWrapper);
//        return list.size() != 0;
    }

    @Override
    public User register(UserDTO userDTO){
        User one = getUserInfo(userDTO);
        if (one == null){
            one = new User();
            BeanUtil.copyProperties(userDTO,one,true);
            save(one);//把copy完之后的用户对象存储到数据库
        }else {
            throw new  ServiceException(Constants.CODE_600,"用户已存在");
        }

        return null;
    }

    private User getUserInfo(UserDTO userDTO){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_number",userDTO.getNo());
        queryWrapper.eq("password",userDTO.getPassword());
        User one;
        try{
            one = getOne(queryWrapper);//从数据库查询信息
        }catch (Exception e){
            LOG.error(e);//打印错误日志
            throw new  ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }

}